import { FC, useState, useEffect } from 'react';
import {
  Card,
  Space,
  Form,
  Input,
  Button,
  Select,
  Table,
  Popconfirm,
  message,
  Pagination,
  Modal,
  DatePicker,
} from 'antd';

import moment from 'moment';

/*
  表格数据：http://pudge.wang:3000/api/cities/manage/list 
  method: POST
  data: {
    city: 城市名称string
    useCar: 用车模式的对应的值string
    operating: 运营模式的对应的值string
    page_size: 每页的条数 number
    current_page: 当前第几页 number
  }
*/

/*
  城市列表： http://pudge.wang:3000/api/cities/list
  method: GET
*/

/*
  删除接口：http://pudge.wang:3000/api/cities/manage/del
  method: POST
  data: {
    id: 数据的_id string
  }
*/

/*
  新增接口: http://pudge.wang:3000/api/cities/manage/add
  method: POST
  data: {
    admin: 表单输入的管理员
    city: 表单选择的城市名称
    handleTime: 当前请求的时候的时间戳
    openTime: 开通时间对应的时间戳
    operating: 运营模式
    useCar: 用车模式
  }

*/

import { tableApi, cityApi, deleteApi, addApi } from '@/utils/api';
import { formatDate } from '@/utils';

// 用车模式的匹配的对象
const useCarObj: any = {
  1: '禁停区',
  2: '停车点',
};
const operatingObj: any = {
  1: '自营',
  2: '加盟',
};

interface cityType {
  id: number;
  nm: string;
  py: string;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const Index: FC = () => {
  // 搜索用的form实例
  const [form] = Form.useForm();
  // 新增用的form实例
  const [form2] = Form.useForm();
  // const [chooseCity, setChooseCity] = useState<string | undefined>(undefined);
  // const [chooseUseCar, setChooseUseCar] = useState<string | undefined>(
  //   undefined,
  // );
  // const [chooseOperating, setChooseOperating] = useState<string | undefined>(
  //   undefined,
  // );
  const [chooseObj, setChooseObj] = useState({});
  const [total, setTotal] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);

  // 控制模态框显示的
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增城市');

  // 用于搜索的提交
  const onFinish = (values: any) => {
    // console.log('Finish:', values);
    // setChooseCity(values.city);
    // setChooseUseCar(values.useCar);
    // setChooseOperating(values.operating);
    setChooseObj(values);
  };
  // 重置表单和表格
  const reset = () => {
    form.resetFields();
    setChooseObj({});
  };

  // 城市数据
  const [cityList, setCityList] = useState<cityType[]>([]);
  // 表格数据
  const [dataSource, setDataSource] = useState([]);
  // 表格的列信息
  const columns = [
    // {
    //   title: '城市ID',
    //   dataIndex: '_id',
    // },
    {
      title: '城市名称',
      dataIndex: 'city',
    },
    {
      title: '用车模式',
      dataIndex: 'useCar',
      render(text: string) {
        return <span>{useCarObj[+text]}</span>;
      },
    },
    {
      title: '营运模式',
      dataIndex: 'operating',
      render(text: string) {
        return <span>{operatingObj[+text]}</span>;
      },
    },
    {
      title: '城市管理员',
      dataIndex: 'admin',
    },
    {
      title: '城市开通时间',
      dataIndex: 'openTime',
      render(text: string) {
        return formatDate(+text);
      },
    },
    {
      title: '操作',
      width: 160,
      render(text: string, record: any) {
        return (
          <Space>
            <Button onClick={() => editOpen(record)}>编辑</Button>
            {/* 二次确认 */}
            <Popconfirm
              title="你确定要删除吗?"
              onConfirm={() => confirm(record)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  useEffect(() => {
    getData();
  }, [chooseObj, pageSize, currentPage]);

  useEffect(() => {
    (async () => {
      const res = await cityApi();
      setCityList(res.cts);
    })();
  }, []);

  // 获取列表
  const getData = async () => {
    const res = await tableApi({
      ...chooseObj,
      page_size: pageSize,
      current_page: currentPage,
    });
    if (res.status === 0) {
      const result = res.result.map((item: any) => ({
        ...item,
        key: item._id,
      }));
      setDataSource(result);
      setTotal(res.total);
    }
  };

  // 删除
  const confirm = async (record: any) => {
    const res = await deleteApi({ id: record._id });
    if (res.status === 0) {
      // 删除是成功的
      message.success('删除成功');
      // 用重新请求接口的方式去刷新页面
      getData();
    }
  };

  // 页码的改变事件
  const pageChange = (page: number, pageSize: number) => {
    // console.log(page);
    // console.log(pageSize);
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  // 打开对话框
  const openModal = () => {
    setModalTitle('新增城市');
    form2.resetFields();
    setIsModalVisible(true);
  };

  // 模态框的确定和取消
  const handleOk = async () => {
    // console.log(form2.getFieldsValue());
    // const arr = form2.getFieldsError().filter((item) => item.errors.length);
    // if (!arr.length && form2.isFieldsTouched(true)) {
    //   console.log(form2.getFieldsValue());
    // }
    try {
      // values是原值
      const values = await form2.validateFields();
      values.openTime = new Date(values.openTime).getTime();
      values.handleTime = new Date().getTime();
      // console.log(values);

      // 判断调哪个接口
      if (modalTitle === '新增城市') {
        const res = await addApi(values);
        if (res.status === 0) {
          message.success('新增成功');
          setIsModalVisible(false);
          getData();
        }
      } else {
        // 调编辑接口
        // values的基础上 ，多加一个这条数据的id
      }
    } catch (errorInfo) {}
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const editOpen = (record: any) => {
    setModalTitle('编辑城市');
    setIsModalVisible(true);

    // console.log(moment(formatDate(+record.openTime)));
    form2.setFieldsValue({
      city: record.city,
      useCar: record.useCar,
      operating: record.operating,
      admin: record.admin,
      openTime: moment(formatDate(+record.openTime)),
    });
  };

  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      <Card>
        {/* 搜索的表单 */}
        <Form
          form={form}
          name="horizontal_login"
          layout="inline"
          onFinish={onFinish}
        >
          <Form.Item name="city" label="城市">
            <Select style={{ width: 120 }} allowClear>
              {cityList.map((item) => (
                <Select.Option value={item.nm} key={item.id}>
                  {item.nm}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="useCar" label="用车模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="operating" label="运营模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={reset}>重置</Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title="城市管理" extra={<Button onClick={openModal}>新增</Button>}>
        {/* 表格的展示 */}
        {/* pagination:false不要显示自带的分页 */}
        <Table dataSource={dataSource} columns={columns} pagination={false} />
        <Pagination
          defaultCurrent={currentPage}
          total={total}
          style={{ marginTop: 15, justifyContent: 'flex-end', display: 'flex' }}
          onChange={pageChange}
          showSizeChanger
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form {...formItemLayout} form={form2} name="add">
          <Form.Item
            name="city"
            label="城市"
            rules={[
              {
                required: true,
                message: '请选择城市!',
              },
            ]}
          >
            <Select allowClear>
              {cityList.map((item) => (
                <Select.Option value={item.nm} key={item.id}>
                  {item.nm}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="useCar"
            label="用车模式"
            rules={[
              {
                required: true,
                message: '请选择用车模式!',
              },
            ]}
          >
            <Select allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="operating"
            label="运营模式"
            rules={[
              {
                required: true,
                message: '请选择运营模式!',
              },
            ]}
          >
            <Select allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="admin"
            label="管理员"
            rules={[
              {
                required: true,
                message: '请输入管理员姓名!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="openTime"
            label="开通时间"
            rules={[
              {
                required: true,
                message: '请选择开通时间!',
              },
            ]}
          >
            <DatePicker />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
};

export default Index;
